package com.yangmao.yangapi_client_sdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.yangmao.yangapi_client_sdk.model.User;
import com.yangmao.yangapi_client_sdk.utils.SignUtils;


import java.util.HashMap;
import java.util.Map;

/**
 * 调用第三方接口的客户端  使用Hutool工具
 *
 * @author yangmao
 */
public class YangApiClient {

    private String accessKey;
    private String secretKey;

    private static final String GATE_HOST = "http://localhost:8090";

    public YangApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name){
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result3= HttpUtil.get(GATE_HOST + "/api/name/", paramMap);
        System.out.println(result3);
        return result3;
    }

    public String getNameByPost(String name){
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);

        String result3= HttpUtil.post(GATE_HOST+"/api/name/", paramMap);
        System.out.println(result3);
        return result3;
    }


    public Map<String,String> getHeaderMap(String body){
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("accessKey",accessKey);
        hashMap.put("body",body);
        hashMap.put("timestamp",String.valueOf(System.currentTimeMillis() / 1000));
        hashMap.put("nonce", String.valueOf(RandomUtil.randomNumbers(1)));
        hashMap.put("sign", SignUtils.genSign(body,secretKey));
        return hashMap;
    }



    public String getUserName(User user){
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post(GATE_HOST+"/api/name/user")
                .addHeaders(getHeaderMap(json))
                .body(json)
                .execute();
        System.out.println(httpResponse.getStatus());
        String body = httpResponse.body();
        return body;

    }


}
